<?php


namespace App\Utils\Helper;


use App\Entity\AdminUserGroup;

class GeneralHelper extends BaseHelper {

    public function __construct () {
        parent::__construct();
    }

    /**
     * User: gao
     * Date: 2019/11/29
     * Description: ~
     * @param string $type
     * @param string $message
     */
    public function addFlash (string $type, string $message) {
        if (!$this->container->has('session')) {
            throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".');
        }

        $this->container->get('session')->getFlashBag()->add($type, $message);
    }

    /**
     * User: Gao
     * Date: 2019-12-27
     * Description: 实现each方法
     * @param $array
     * @return array|bool
     */
    public static function myEach (&$array) {
        $res = [];
        $key = key($array);
        if ($key !== null) {
            next($array);
            $res[1] = $res['value'] = $array[$key];
            $res[0] = $res['key'] = $key;
        } else {
            $res = false;
        }
        return $res;
    }

    /**
     * User: gao
     * Date: 2020/3/20
     * Description: 获取管理员用户组名称
     * @param $id
     * @return string
     */
    public function getAdminUserGroupNameById ($id) {
        $result = '-';

        $obj = $this->entity_manager->getRepository(AdminUserGroup::class)->find($id);
        if (is_object($obj)) {
            $result = $obj->getName();
        }

        return $result;
    }

    /**
     * User: Gao
     * Date: 2020/4/3
     * Description: 是否为超级管理员
     * @param $admin_user_group_id
     * @return bool
     */
    public function isSuperAdmin ($admin_user_group_id) {
        $result = false;

        $admin_user_group = $this->container->get('doctrine.orm.default_entity_manager')->getRepository(AdminUserGroup::class)->findOneBy(['id' => $admin_user_group_id, 'is_super' => true]);
        $result = is_object($admin_user_group);

        return $result;
    }

    /**
     * User: Gao
     * Date: 2020/3/21
     * Description: 获取模块sonata_admin集合
     * @param $admin_user_group_id
     * @return mixed
     */
    public function getModuleSonataAdminsByAdminUserGroupId ($admin_user_group_id) {
        return $this->entity_manager->getRepository(AdminUserGroup::class)->getSonataAdminById($admin_user_group_id);
    }

    /**
     * User: Gao
     * Date: 2020/4/16
     * Description: 随机生成要求位数个字符
     * @param $length
     * @return string|null
     */
    public static function getRandChar ($length) {
        $result = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; //字母以及数字
        $max = strlen($strPol) - 1;
        for ($i = 0; $i < $length; $i++) {
            $result .= $strPol[rand(0, $max)];
        }
        return $result;
    }
}